package com.cmzj21.springcloud.controller;

import com.cmzj21.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author cmzj21
 */
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "globalFallback")
public class OrderHystrixController {
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/ok/{id}")
    public String ok(@PathVariable("id") Integer id){
        return paymentHystrixService.ok(id);
    }

    /**
     * 调用支付服务提供者
     * @param id 随便一个整形数
     * @return 返回服务结果
     */
    @GetMapping("/consumer/payment/failed/{id}")
    @HystrixCommand(fallbackMethod = "paymentTimeoutFallbackMethod", commandProperties = {
            //@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "5000")
    })
    public String failed(@PathVariable("id") Integer id){
        return paymentHystrixService.failed(id);
    }

    /**
     * 调用支付服务提供者,fallback用全局
     * @param id 随便一个整形数
     * @return  返回服务结果
     */
    @GetMapping("/consumer/payment/failed/global/{id}")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2500")
    })
    public String failedGlobal(@PathVariable("id") Integer id){
        return paymentHystrixService.failed(id);
    }

    public String paymentTimeoutFallbackMethod(@PathVariable("id") Integer id){
        return "我是消费者80，对方支付系统服务繁忙，请10秒钟后再试o(╥﹏╥)o" + id;
    }

    public String globalFallback(){
        return "这里是全局fallback处理";
    }
}
